{extend name="layout"/}
{block name="content"}
<body>
<div id="app" class="vueBox">
    <div class="plan-finish-header">
        <div class="plan-finish-bg"></div>
    </div>
    <div class="plan-finish-calendar mtop1">
        <div class="calendar">
            <ul class="month bottom-line">
                <li class="arrow" @click="pickPre(currentYear, currentMonth)"><i class="mintuifont mintui-arrowright arrowleft"></i></li>
                <li class="year-month"><span>{{currentYear}}年{{currentMonth}}月</span></li>
                <li class="arrow" @click="pickNext(currentYear, currentMonth)"><i class="mintuifont mintui-arrowright"></i></li>
            </ul>
            <ul class="weekdays">
                <li>日</li><li>一</li><li>二</li><li>三</li><li>四</li><li>五</li><li>六</li>
            </ul>
            <ul class="days bottom-line">
                <li v-for="(day, index) in days" :key="index">
						<span :day="day.day" class="day-li" :class="{'day-checked':day.isChecked|| isToday(day.day)}" @click="dayCheck(day)">
							<span class="day-span"
                                  :class="{other: currentMonth != day.day.getMonth()+1, 'day-sign': day.isSign,'day-signed': day.isSigned}"
                            >{{day.day.getDate()}}</span>
						</span>
                </li>
            </ul>
        </div>
        <div class="plan-calendar-info" style="">
            <div class="calendar-info-date"><span>{{currentPlan.date}}</span></div>
            <div class="calendar-info-title"><span>{{currentPlan.title}}</span></div>
            <ul class="calendar-info-list">
                <li v-for="(p, i0) in currentPlan.list" :key="i0"><span>{{p}}</span></li>
            </ul>
            <!-- <div class="calendar-info-text">
                <p>学习考点：成本管理</p>
                <p class="calendar-info-nums">完成题目：100道</p>
            </div> -->
        </div>
    </div>
    <div class="sign-btn">
        <button class="show-map" onclick="showMap()">查看签到位置</button>
        <button v-if="showSignBtn" @click="handleSign">立即签到</button>
    </div>
</div>
{/block}
{block name="script"}
<script src="/static/mob/js/calendar.js"></script>
<script>
    new Vue({
        el: '#app',
        data: function () {
            return {
                // 日历
                currentDay: 1, // 当前天
                currentMonth: 1, // 当前月
                currentYear: 1970,
                currentWeek: 0, // 一号所在的星期
                days: [], // 当月所有天数
                content: {},
                sign_days: [], // 签到日期
                is_sign: false,
                currentPlan: {},
                showSignBtn: true,
            }
        },
        created: function () {
            // var td = new Date();
            // this.todayDate = td.getFullYear() + '/' + (td.getMonth() + 1) + '/' + td.getDate();
            // console.log(this.todayDate)
            this.todaySign();
        },
        methods: {
            isToday: function (day) {
                var now = new Date();
                return day.getFullYear() + '/' + (day.getMonth() + 1) + '/' + day.getDate() == now.getFullYear() + '/' + (now.getMonth() + 1) + '/' + now.getDate();
            },
            /**
             * 获取签到日期
             */
            handleReq: function(param, cb) {
                var _this = this;
                param = param|| {};
                axios.get(URL_SIGN_DAYS, {
                    params:param
                }).then(function(res) {
                    _this.sign_days = res.data.data;
                    cb && cb()
                });
            },
            todaySign: function () {
                var _this = this;
                this.handleReq({},function(){
                    _this.initData(null);
                    var d = new Date();
                    _this.dayCheck({
                        day: d,
                        isSign: _this.isVerDate(d),
                        isSigned: _this.isSigned(d),
                    })
                });
            },
            initData: function (cur) {
                var date;
                if (cur) { // 切换上一月、下一月
                    date = new Date(cur);
                } else {
                    var now = new Date(); // 此处取本机时间，应改为服务器时间
                    var d = new Date(this.formatDate(now.getFullYear(), now.getMonth() + 1, 1));
                    d.setDate(35); // 设置天数为35天（32~59都可以，既设置到下一个月的某一天）
                    date = new Date(this.formatDate(d.getFullYear(), d.getMonth(), 1));
                }
                this.currentDay = new Date().getDate(); // 今日日期 几号
                this.currentYear = date.getFullYear(); // 当前年份
                this.currentMonth = date.getMonth() + 1; // 当前月份
                this.currentWeek = date.getDay(); // 当前月1号是星期几？ 0表示星期天

                // 当前月最后一天是星期几？ 0表示星期天
                this.nextWeek = new Date(date.getFullYear(), date.getMonth() + 1, 0).getDay();
                var str = this.formatDate(this.currentYear, this.currentMonth, 1); // 2020/01/01
                var nextStr = new Date(date.getFullYear(), date.getMonth() + 1, 0).toLocaleDateString(); // 2020/01/01
                // console.log(nextStr)
                this.days = []; // 初始化日期
                // 设置上一个月 需显示 的最后几天  铺满一周
                for (var i = this.currentWeek; i > 0; i--) {
                    var d = new Date(str);
                    d.setDate(d.getDate() - i);
                    var dayobject = {
                        day: d,
                        isSign: this.isVerDate(d),
                        isSigned: this.isSigned(d)
                    }; // 用一个对象包装Date对象  以便为以后预定功能添加属性
                    this.days.push(dayobject); // 将日期放入data 中的days数组 供页面渲染使用
                }
                // 显示当前月的天数  第二个循环为 j<= 36- this.currentWeek，
                // 因为1号是星期六的时候当前月需显示6行，如2020年8月
                this.num = 0; //第几个月 每遇到1号加1
                for (var j = 0; j <= 36 - this.currentWeek; j++) {
                    var d = new Date(str);
                    d.setDate(d.getDate() + j);
                    var dddd = d.getDate();
                    var dayobject = {
                        day: d,
                        isSign: this.isVerDate(d),
                        isSigned: this.isSigned(d)
                    };
                    if (dddd == 1) {
                        this.num++
                    }
                    if (this.num == 2) {
                        break
                    }
                    this.days.push(dayobject);
                }
                // console.log('当前月1号是星期' + this.currentWeek)
                // console.log('当前月最后一天是星期' + this.nextWeek)
                // 设置下一个月 需显示 的最前几天铺满一周
                for (var k = 1; k <= 6 - this.nextWeek; k++) {
                    var d = new Date(nextStr);
                    d.setDate(d.getDate() + k);
                    var dayobject = {
                        day: d,
                        isSign: this.isVerDate(d),
                        isSigned: this.isSigned(d)
                    }; // 用一个对象包装Date对象  以便为以后预定功能添加属性
                    this.days.push(dayobject); // 将日期放入data 中的days数组 供页面渲染使用
                }
            },
            /**
             * 判断该日期是否有任务
             * @param d
             * @returns {boolean}
             */
            isVerDate: function (d) {
                var signdays = [];
                for (var i in this.sign_days) {
                    signdays.push(this.sign_days[i].day);
                }
                return signdays.includes(d.toLocaleDateString());
            },
            /**
             * 判断该日期是否有任务并且已完成
             * @param d
             * @returns {boolean}
             */
            isSigned: function (d) {
                var signdays = [];
                for (var i in this.sign_days) {
                    if (this.sign_days[i].is_sign) {
                        signdays.push(this.sign_days[i].day);
                    }
                }
                return signdays.includes(d.toLocaleDateString());
            },
            // 按天获取当天的签到记录
            getDayData:function(d){
                for (var i in this.sign_days) {
                    if (d.day.getFullYear() + '/' + (d.day.getMonth() + 1) + '/' + d.day.getDate() == this.sign_days[i].day) {
                        this.$set(d, 'list', this.sign_days[i].list);
                        break;
                    }
                }
            },
            /**
             * 上一月
             * @param year
             * @param month
             */
            pickPre: function (year, month) {
                var _this = this;
                this.handleReq({y:(month==1 ? year-1 : year),m: (month==1 ? 12 : month-1)},function(){
                    var d = new Date(_this.formatDate(year, month, 1));
                    d.setDate(0);
                    _this.initData(_this.formatDate(d.getFullYear(), d.getMonth() + 1, 1));
                });
            },
            /**
             * 下一月
             * @param year
             * @param month
             */
            pickNext: function (year, month) {
                var _this = this;
                this.handleReq({y:(month==12 ? year+1 : year),m: (month==12 ? 1 : month+1)},function(){
                    var d = new Date(_this.formatDate(year, month, 1));
                    d.setDate(35);
                    _this.initData(_this.formatDate(d.getFullYear(), d.getMonth() + 1, 1));
                });
            },
            // 返回 类似 2020/01/01 格式的字符串
            formatDate: function (year, month, day) {
                month < 10 && (month = '0' + month);
                day < 10 && (day = '0' + day);
                var data = year + '/' + month + '/' + day;
                return data;
            },
            /**
             * 点击日期查询
             * @param index
             */
            dayCheck: function (day) {
                // console.log(this.isToday(day));
                this.showSignBtn = this.isToday(day.day);
                var currentPlan = {
                    title: '',
                    date: '',
                    list: []
                };
                currentPlan.date = day.day.toLocaleDateString().split('/')[1] + '月' + day.day.toLocaleDateString().split('/')[2] + '日';
                for (var i in this.days) {
                    this.$set(this.days[i], 'isChecked', 0)
                }
                this.$set(day, 'isChecked', 1);
                this.getDayData(day);
                if (day.isSign) {
                    if (day.isSigned) {
                        if(day.list)
                        currentPlan.list = day.list;
                        currentPlan.title = '已签到' + currentPlan.list.filter((num) => {
                            return !(num == '未签到' || num == '未签退');
                        }).length + '次';
                    } else {
                        currentPlan.title = '未签到'
                    }

                } else {
                    currentPlan.title = '暂无签到'
                }
                this.currentPlan = currentPlan
            },
            // 签到
            handleSign: function() {
                var _this = this;
                axios.get(URL_SIGN_DO, {
                    params:{
                        lat: latValue,
                        lng: lngValue,
                    }
                }).then(function(res) {
                    vant.Toast(res.data.msg);
                    _this.todaySign();
                });
            }
        }
    });

    // JavaScript Document
    (function px2rem(doc, win) {
        var docEl = doc.documentElement,
            resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
            recalc = function () {
                var clientWidth = docEl.clientWidth;
                if (!clientWidth) return;
                docEl.style.fontSize = 100 * (clientWidth / 750) + 'px';
                /*
                 * 100 -> html,body {  font-size:100px; }
                 * 750 -> 此处以 iPhone6 两倍设计稿 宽度750px 布局页面
                 * 根据具体情况改变这两个数值
                 */
            };
        if (!doc.addEventListener) return;
        // 窗口大小发生变化，初始化
        win.addEventListener(resizeEvt, recalc, false);
        doc.addEventListener('DOMContentLoaded', recalc, false);
        //防止在html未加载完毕时执行，保证获取正确的页宽
        setTimeout(function () {
            px2rem(doc, win);
        }, 200);
    })(document, window);
</script>
<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
<script>
    var jsconfig = JSON.parse('{$jsconfig|raw}');
    var latValue= 0;
    var lngValue= 0;
    var latDb= {$lat_db?:0};
    var lngDb= {$lng_db?:0};
    wx.config(jsconfig);
    var desc = "",
        share_title = "",
        share_url = "";
    wx.ready(function(){
        // var wxData = {
        //     title: share_title,
        //     link: share_url,
        //     desc: desc,
        //     imgUrl: img_url,
        // };
        // wx.onMenuShareTimeline(wxData);
        // wx.onMenuShareAppMessage(wxData);
        // wx.onMenuShareQQ(wxData);
        // wx.onMenuShareWeibo(wxData);
        // wx.onMenuShareQZone(wxData);
        wx.getLocation({
            type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
            success: function (res) {
                latValue = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                lngValue = res.longitude; // 经度，浮点数，范围为180 ~ -180。
                // var speed = res.speed; // 速度，以米/每秒计
                // var accuracy = res.accuracy; // 位置精度
                console.log(latitude, longitude)
                // alert(latitude + " "+longitude)
                if(latValue == false || lngValue == false) {
                    vant.Toast('为获取到坐标信息');
                }
            }
        });
    });
    function showMap() {
        if(!latDb || !lngDb) {
            vant.Toast('未设置签到位置');
            return
        }
        wx.ready(function(){
            wx.openLocation({
                latitude: latDb, // 纬度，浮点数，范围为90 ~ -90
                longitude: lngDb, // 经度，浮点数，范围为180 ~ -180。
                name: '签到位置', // 位置名
                address: '请到签到卡位置附近操作', // 地址详情说明
                scale: 16, // 地图缩放级别,整形值,范围从1~28。默认为最大
                infoUrl: '' // 在查看位置界面底部显示的超链接,可点击跳转
            });
        });
    }

    wx.error(function(res){
        console.log(res);
        vant.Toast('微信接口对接错误：',JSON.stringify(res));
    });
</script>
{/block}